try:
  import json
except ImportError:
  import simplejson as json
import logging
import sys
import urllib
import urllib2

# Work around threading issue in MacOS 10.6
urllib2.install_opener(urllib2.build_opener())

class Fetcher(object):
  def __init__(self, url, **params):
    if params:
      url = '%s?%s' % (url, urllib.urlencode(params))
    self.url = url

  def get(self, preprocessor=None, object_hook=None):
    kwargs = {}
    if sys.version_info >= (2, 6):
      # TODO(logan): Needs a way to be configured.
      kwargs['timeout'] = 30
    logging.info('JSON GET from %s', self.url)
    f = urllib2.urlopen(self.url, **kwargs)
    if preprocessor:
      content = preprocessor(f.read())
      return json.loads(content, object_hook=object_hook)
    else:
      return json.load(f, object_hook=object_hook)
    

def get(url, **params):
  return Fetcher(url, **params).get()
